import arrow
import mongoengine as db

from app.db import BaseDocument, BaseEmbeddedDocument
from app.db.models.alerts import Notification


class SettingVul(BaseEmbeddedDocument):
    critical = db.IntField(default=0, min_value=0, max_value=1048575)
    high = db.IntField(default=0, min_value=0, max_value=1048575)
    medium = db.IntField(default=0, min_value=0, max_value=1048575)
    low = db.IntField(default=0, min_value=0, max_value=1048575)


class SettingSecurityEvent(BaseEmbeddedDocument):
    black_links = db.IntField(default=0, min_value=0, max_value=1048575)
    broken_links = db.IntField(default=0, min_value=0, max_value=1048575)
    cryjack = db.BooleanField(default=True)
    malscan = db.BooleanField(default=True)
    foreign_links = db.IntField(default=0, min_value=0, max_value=1048575)


class Settings(BaseEmbeddedDocument):
    vul = db.EmbeddedDocumentField(document_type=SettingVul, default=SettingVul)
    securityEvent = db.EmbeddedDocumentField(document_type=SettingSecurityEvent, default=SettingSecurityEvent)


class UrlBlackListSettings(BaseDocument):
    meta = {
        'collection': 'url_blacklist_setting',
    }

    job_id = db.ObjectIdField(required=True)
    uid = db.ObjectIdField(required=True)
    settings = db.EmbeddedDocumentField(document_type=Settings, default=Settings)
    create_time = db.DateTimeField(required=True)
    updateTime = db.DateTimeField(required=True)
    alertGroupIds = db.ListField(default=[])
    notification = db.EmbeddedDocumentField(default=Notification, document_type=Notification)

    def save(self, *args, **kwargs):
        now_datetime = arrow.utcnow().datetime
        if not self.create_time:
            self.create_time = now_datetime
        self.updateTime = now_datetime
        return super(UrlBlackListSettings, self).save(*args, **kwargs)

    def update(self, **kwargs):
        kwargs['updateTime'] = arrow.utcnow().datetime
        return super(UrlBlackListSettings, self).update(**kwargs)
